package gaincapital;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Main {
	public static void main(String[] args) throws MalformedURLException, IOException {
		List<String> urls = new ArrayList<String>();
		// urls.add("http://ratedata.gaincapital.com/2014/06%20June/EUR_USD_Week1.zip");
		// http://ratedata.gaincapital.com/2014/06%20June/EUR_USD_Week1.zip
		// http://ratedata.gaincapital.com/2014/05%20May/EUR_USD_Week1.zip
		// http://ratedata.gaincapital.com/2014/04%20April/EUR_USD_Week2.zip
		// http://ratedata.gaincapital.com/2014/03%20March/EUR_USD_Week1.zip
		// http://ratedata.gaincapital.com/2014/02%20February/EUR_USD_Week1.zip
		// http://ratedata.gaincapital.com/2014/01%20January/EUR_USD_Week1.zip

		// for (int i = 1; i <= 5; i++) {
		// urls.add("http://ratedata.gaincapital.com/2014/06%20June/EUR_USD_Week"
		// + i + ".zip");
		// }
		// for (int i = 1; i <= 4; i++) {
		// urls.add("http://ratedata.gaincapital.com/2014/05%20May/EUR_USD_Week"
		// + i + ".zip");
		// }
		// for (int i = 2; i <= 5; i++) {
		// urls.add("http://ratedata.gaincapital.com/2014/04%20April/EUR_USD_Week"
		// + i + ".zip");
		// }
		// for (int i = 1; i <= 5; i++) {
		// urls.add("http://ratedata.gaincapital.com/2014/03%20March/EUR_USD_Week"
		// + i + ".zip");
		// }
		// for (int i = 1; i <= 4; i++) {
		// urls.add("http://ratedata.gaincapital.com/2014/02%20February/EUR_USD_Week"
		// + i + ".zip");
		// }
		for (int i = 1; i <= 4; i++) {
			urls.add("http://ratedata.gaincapital.com/2014/01%20January/EUR_USD_Week" + i + ".zip");
		}
		for (String url : urls) {
			saveUrl(getFileName(url), url);
			System.out.println(getFileName(url));
		}
	}

	public static void saveUrl(final String filename, final String urlString) throws MalformedURLException, IOException {
		BufferedInputStream in = null;
		FileOutputStream fout = null;
		try {
			in = new BufferedInputStream(new URL(urlString).openStream());
			fout = new FileOutputStream(filename);

			final byte data[] = new byte[1024];
			int count;
			while ((count = in.read(data, 0, 1024)) != -1) {
				fout.write(data, 0, count);
			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (fout != null) {
				fout.close();
			}
		}
	}

	private static String getFileName(String str) {
		return str.substring(str.indexOf("/2014") + 1).replaceAll("/", "_").replaceAll("%20.*_", "_");
	}
}
